#打开文件
try:
    f = open('game.txt')
    print('file existed')
    f.close()
except:
    f = open('game.txt','w')
    print('a new file is initiated')
    f.close()
#游戏开始
import requests
game_rounds = 0
game_times = 0
game_min = 0
while True:
    try:
        selection = int(input('1 for start,0 for stop'))
        if selection != 0 and selection != 1:
            print('选0或者1，输入无效')
            continue
    except:
        print('别乱输入东西哦，输入无效')
        continue

    if selection == 1:
        r = requests.get('https://python666.cn/cls/number/guess/')
        num = int(r.text)
        game_min0 = 0
        while True:
            try:
                temp = int(input('请输入1到100的一个整数'))
                if temp < 1:
                    print('你输入的太小了，输入无效')
                    continue
                elif temp >100:
                    print('你输入的太大了，输入无效')
                    continue
            except:
                print('别乱输入东西哦，输入无效')
                continue
#以上是判断输入是否错误
            game_rounds += 1
            game_min0 += 1
            if temp < num:
                print('太小了')
            elif temp > num:
                print('太大了')
            else:
                print('中了')
                break
        if game_min == 0 or game_min0 < game_min:
                game_min = game_min0
        game_times = game_times+1
        average_bingo = game_rounds/game_times
    else:
        break
try:
    print('game_times:%d game_min:%d game_rounds:%d average_bingo:%d\n'%(
            game_times,game_min,game_rounds,average_bingo))
    print('game over')
    #输入名字，保存结果
    name = input('what\'s your name?')
    with open('game.txt','r') as f:
        scores = f.readlines()
        print(scores) #检查
        scores_new = []
        for i in scores:
            name_0 = i.split()[0]
            if name != name_0:
                scores_new.append(i)
            else:
                lst = []
                score_existed = i.split()
                for j in score_existed[1:-1]:
                    lst.append(int(j.split(':')[1]))
                game_times += lst[0]
                game_rounds += lst[2]
                if lst[1] < game_min:
                    game_min = lst[1]
                average_bingo = game_rounds / game_times
        scores_new.append(name+' game_times:%d game_min:%d game_rounds:%d average_bingo:%.1f\n'%(
            game_times,game_min,game_rounds,average_bingo))
        print(scores_new)  # 检查
        with open('game.txt','w') as n:
            n.writelines(scores_new)
except:
    print('game over')
